import asyncio
import aiohttp


"""消费者和生产者模型"""
def consumer():
    status = True
    while True:
        n = yield status
        print(f"我拿到了{n}")
        if n == 3:
            status = False


def producer(consumer, n):
    while n > 0:
        yield consumer.send(n)
        n -= 1


"""同时开始多个工作"""
async def run_syn():
    print('开始工作')
    await asyncio.sleep(1)
    print('完成工作')


async def main(n):
    a = []
    for _ in range(n):
        a.append(run_syn())
    await asyncio.gather(*a)


url_array = ["https://www.jd.com/"] * 10


"""异步网络请求"""
async def request(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            result = response.status
            return result


if __name__ == '__main__':

# =============================== 第一题
    asyncio.run(main(3))

# =============================== 第二题
    c = consumer()
    c.send(None)
    p = producer(c, 5)
    for status in p:
        if status is False:
            print("当前 n 小于 3")
            break
    print("Done!")


# ================================ 第三题
    loop = asyncio.get_event_loop()
    task_array = [request(url) for url in url_array]
    result = loop.run_until_complete(asyncio.gather(*task_array))
    loop.close()
    print(result)
